package com.learn.security.service.impl;

import com.learn.security.domain.SysRole;
import com.learn.security.domain.SysUser;
import com.learn.security.domain.SysUserRole;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @auther liuhw
 * @date 2020/3/17 14:01
 * @description:
 * @since 1.0
 **/
@Service("userDetailsService")
public class UserDetailService implements UserDetailsService {
    private Logger logger = LoggerFactory.getLogger(UserDetailService.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Collection<GrantedAuthority> authorities = new LinkedList<>();

        // 获取用户
        SysUser user = userService.getByName(username);

        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException(username + " cannot be found.");
        }

        // 添加权限
        List<SysUserRole> roleList = userRoleService.listByUserId(user.getId());
        if (logger.isTraceEnabled()) {
            logger.info("用户 {} 角色为 {}", username, Arrays.toString(roleList.parallelStream().map(userRole -> roleService.getById(userRole.getRoleId()).getName()).toArray()));
        }
        for (SysUserRole userRole : roleList) {
            SysRole role = roleService.getById(userRole.getRoleId());
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        // 返回UserDetails实现类
        return new User(user.getName(), user.getPassword(), authorities);
    }
}
